﻿using System;
using System.IO;
using System.Linq;


namespace Program07
{
    /// <summary>
    /// 利用FileStream实现文件的复制
    /// </summary>
    class Program
    {
        private static void Main(string[] args)
        {
            var source = "1.txt";
            var target = "2.txt";
            CopyFile(source,target);
            Console.WriteLine("Copy Successed!");
        }

        //文件流的复制
        public static void CopyFile(string source, string target)
        {
            //先读取文件流
            using (FileStream fsRead = new FileStream(source, FileMode.OpenOrCreate, FileAccess.Read))
            {
                //写入新文件
                using (FileStream fsWrite = new FileStream(target, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    //读写文件的缓冲区
                    byte[] buffer = new byte[1024 * 1024 * 10];

                    //用循环读取文件流,如果源文件大于缓冲区，就需要反复都读取写入
                    while (true)
                    {
                        //返回本次读取的实际字节数
                        int r = fsRead.Read(buffer, 0, buffer.Length);
                        //如果读到0，说明读取完成，跳出循环
                        if (r == 0)
                            break;

                        //写入文件
                        fsWrite.Write(buffer, 0, r);
                    }
                }
            }
        }
    }
}
